package com.cz.zslu.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.zslu.common.ReturnObject;
import com.cz.zslu.entity.ProductInquiry;
import com.cz.zslu.entity.ProductQuote;
import com.cz.zslu.entity.SysUser;
import com.cz.zslu.interceptor.BaseContextHandler;
import com.cz.zslu.interceptor.IgnoreAuth;
import com.cz.zslu.model.Parts;
import com.cz.zslu.rest.BaseController;
import com.cz.zslu.service.ISysUserService;
import com.cz.zslu.service.ProductInquiryService;
import com.cz.zslu.service.ProductQuoteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 询价管理 前端控制器
 * </p>
 *
 * @author Bruce
 * @since 2019-06-20
 */
@RestController
@RequestMapping("/sys/inquire")
@Api(description = "询价管理")
public class ProductInquiryController extends BaseController<ProductInquiryService, ProductInquiry> {

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ProductQuoteService productQuoteService;


    @ApiOperation("获取我的询价动态分页")
//    @IgnoreAuth
    @RequestMapping(value = "/getMyInquiryPage", method = RequestMethod.POST)
    public ReturnObject<List<ProductInquiry>> getAllNewPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                            @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                            @ApiParam("类型（0、未报价，1、已报价）：") @RequestParam Integer type) {

        SysUser sysUser = iSysUserService.selectById(BaseContextHandler.getUserID());
        EntityWrapper<ProductInquiry> ew = new EntityWrapper<>();
        ew.eq("state", 0);
        ew.eq("type", type);
        ew.eq("inquirer_id", sysUser.getId());
        ew.orderBy("crt_time", false);
        Page<ProductInquiry> obj = baseService.selectPage(new Page<>(offset, limit), ew);
        if (obj.getRecords() != null && obj.getRecords().size() > 0) {
            for (ProductInquiry productInquiry : obj.getRecords()) {
                List<ProductQuote> productQuotes = null;
                if (type == 0) {
                    productQuotes = new ArrayList<ProductQuote>();
                } else {
                    productQuotes = productQuoteService.selectList(new EntityWrapper<ProductQuote>().eq("product_inquiry_id", productInquiry.getId()));
                }
                productInquiry.setProductQuotes(productQuotes);
            }
        }

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("获取详情")
//    @IgnoreAuth
    @RequestMapping(value = "/findInfoById", method = RequestMethod.POST)
    public ReturnObject<ProductInquiry> findInfoById(@ApiParam("id") @RequestParam Long id) {

        ProductInquiry productInquiry = baseService.selectById(id);
        List<ProductQuote> productQuotes = null;
        if (productInquiry.getType() != 0) {
            productQuotes = productQuoteService.selectList(new EntityWrapper<ProductQuote>().eq("product_inquiry_id", id));
        } else {
            productQuotes = new ArrayList<>();
        }
        productInquiry.setProductQuotes(productQuotes);
        return new ReturnObject<>(0, "获取成功", productInquiry);
    }

    @ApiOperation("新增")
    @RequestMapping(value = "/saveProductInquiry", method = RequestMethod.POST)
    public ReturnObject<ProductInquiry> saveProductInquiry(@ApiParam("配件清单集合") @RequestParam String partsList,
                                                           @ApiParam("品质范围（0：全新国产，1：原装进口，2：拆车件/再制造）") @RequestParam Integer property,
                                                           @ApiParam("发票类型（0：不需要开发票，1：普通发票，2：增值税发票)") @RequestParam Integer invoiceType,
                                                           @ApiParam("图片附件") @RequestParam String picUrl,
                                                           @ApiParam("备注") @RequestParam String remark
    ) {
        SysUser sysUser = iSysUserService.selectById(BaseContextHandler.getUserID());
        List<Parts> partss = JSONArray.parseArray(partsList, Parts.class);
        if (partss != null) {
            for (Parts parts : partss) {
                ProductInquiry info = new ProductInquiry();
                info.setName(parts.getName());
                info.setCount(parts.getCount());
                info.setOemSerial(parts.getOemSerial());
                info.setPicUrl(picUrl);
                info.setInvoiceType(invoiceType);
                info.setRemark(remark);
                info.setProperty(property);
                info.setInquirerId(sysUser.getId());
                info.setState(0);
                info.setStatus(0);
                info.setType(0);
                baseService.insert(info);
            }
        }
        return new ReturnObject<>(0, "新增成功", null);
    }

    @ApiOperation("修改")
    @RequestMapping(value = "/editProductInquiry", method = RequestMethod.POST)
    public ReturnObject<ProductInquiry> editProductInquiry(@ApiParam("询价id") @RequestParam Long id,
                                                           @ApiParam("配件名称") @RequestParam String name,
                                                           @ApiParam("数量") @RequestParam Integer count,
                                                           @ApiParam("OEM号/留言") @RequestParam String oemSerial,
                                                           @ApiParam("品质范围（0：全新国产，1：原装进口，2：拆车件/再制造）") @RequestParam Integer property,
                                                           @ApiParam("发票类型（0：不需要开发票，1：普通发票，2：增值税发票)") @RequestParam Integer invoiceType,
                                                           @ApiParam("图片附件") @RequestParam String picUrl,
                                                           @ApiParam("备注") @RequestParam String remark
    ) {
        ProductInquiry info = baseService.selectById(id);
        info.setName(name);
        info.setCount(count);
        info.setOemSerial(oemSerial);
        info.setPicUrl(picUrl);
        info.setInvoiceType(invoiceType);
        info.setRemark(remark);
        info.setProperty(property);
        baseService.updateById(info);
        return new ReturnObject<>(0, "修改成功", null);
    }

    @ApiOperation("删除我的询价")
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public ReturnObject del(@ApiParam("id") @RequestParam Long id) {
        ProductInquiry info = baseService.selectById(id);
        info.setState(1);
        baseService.updateById(info);
        return new ReturnObject<>(0, "删除成功");
    }

    @ApiOperation("打开/关闭我的询价")
    @RequestMapping(value = "/open", method = RequestMethod.POST)
    public ReturnObject open(@ApiParam("询价id") @RequestParam Long id, @ApiParam("关闭询价状态 0、打开 1、关闭") @RequestParam Integer status) {
        ProductInquiry info = baseService.selectById(id);
        info.setStatus(status);
        baseService.updateById(info);
        return new ReturnObject<>(0, "操作成功");
    }


    @ApiOperation("获取后台询价动态分页")
//    @IgnoreAuth
    @RequestMapping(value = "/getAllInquiryPage", method = RequestMethod.POST)
    public ReturnObject<List<ProductInquiry>> getAllInquiryPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                                @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                                @ApiParam("产品性质（0：全新国产，1：原装进口，2：拆车件/再制造）") @RequestParam Integer property,
                                                                @ApiParam("类型（0、未报价，1、已报价）") @RequestParam Integer type,
                                                                @ApiParam("配件名称") @RequestParam String pname) {

        EntityWrapper<ProductInquiry> ew = new EntityWrapper<>();
        ew.eq("state", 0);
        if (type != null) {

            ew.eq("type", type);
        }
        if (property != null) {

            ew.eq("property", property);
        }
        if(StringUtils.isNotBlank(pname)){
            ew.andNew().like("name", pname).or().like("oem_serial", pname);
        }
        ew.orderBy("crt_time", false);
        Page<ProductInquiry> obj = baseService.selectPage(new Page<>(offset, limit), ew);
//        if (obj.getRecords() != null && obj.getRecords().size() > 0) {
//            for (ProductInquiry productInquiry : obj.getRecords()) {
//                List<ProductQuote> productQuotes = null;
//                if (type == 0) {
//                    productQuotes = new ArrayList<ProductQuote>();
//                } else {
//                    productQuotes = productQuoteService.selectList(new EntityWrapper<ProductQuote>().eq("product_inquiry_id", productInquiry.getId()));
//                }
//                productInquiry.setProductQuotes(productQuotes);
//            }
//        }

        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

}

